import wxutil from '../../utils/wxutil'
const app = getApp();

Page({
  data: {
    imageLoadError: false,
    closeFlag:true,
    formState: {
      // 姓名
      name: '',
      // 身份证号
      user_id: '111',
      // 人像面
      id_card_front: '',
      // 国徽面
      id_card_back: '',
      // 户籍性质
      household_nature: '',
      address: '',
      // 银行卡号
      bank_account: '',
      // 发卡银行
      bank_branch: '',
      // 手机号
      phone: '',
      payment_amount: '',
      insurance_status: undefined,
      insurance_base: '',
      social_security_image: '',
      housing_fund_image: ''
    },
    openImg: false,
    openImg2: false,
    imgsrc: '',
    openImg1: false,
    showModal: false, // 控制模态框的显示和隐藏
    modalTitle: '', // 模态框标题
    modalContent: '', // 模态框内容
    userInfo: {},
    avatarUrl: './images/default.jpg', // 默认头像
    showActionSheet: false,
    flag: false,
    flag1: false,
    openId: undefined,
    desc: '',
    modalFlag: false,
    isFromImagePreview: false,
    isCheckingLogin: true, // 添加登录检查状态标志
    showIdCardsSection: false, // 身份证照片弹出框状态
    showLoginModal: false, // 控制登录选择弹窗的显示
    avatarFlag: undefined
  },

  goInformation: function () {
    if (!wx.getStorageSync('modalFlag')) {
      this.setData({
        'modalFlag': true
      })
    } else {
      wx.navigateTo({
        url: '/pages/supplement/supplement'
      });
    }
  },

  showIdCards: function () {
    if (this.data.formState.id_card_front && this.data.formState.id_card_back) {
      this.setData({
        showIdCardsSection: true,
      });
    } else {
      wx.showToast({
        title: "暂无",
        icon: "none"
      });
    }

  },

  goBank:function(){
    wx.navigateTo({
      url: '/pages/bankcard/bankcard' // 请根据实际的银行卡页面路径修改
    });
  },

  privacyBtn: function () {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    });
  },

  protocolBtn: function () {
    wx.navigateTo({
      url: '/pages/protocol/protocol'
    });
  },
  previewImage: function (e) {
    const imgsrc = e.currentTarget.dataset.src; // 获取点击的图片路径
    if (imgsrc) {
      this.setData({
        isFromImagePreview: true,
      })

      wx.previewImage({
        current: imgsrc, // 当前要显示的图片 URL
        urls: [imgsrc], // 需要预览的图片 URL 列表数组
        success: () => {
          console.log("图片预览成功");
        },
        fail: (err) => {
          console.error("图片预览失败", err);
        }
      });
    } else {
      wx.showToast({
        title: "图片加载失败",
        icon: "none"
      });
    }
  },
  

  confirmAction: function () {
    this.setData({
      'modalFlag': false
    })
    wx.setStorageSync('modalFlag', true)
    wx.navigateTo({
      url: '/pages/supplement/supplement'
    });
  },

  closeLoginOverlay: function() {
    // Just close the overlay but keep isLoggedIn status
    // this.setData({
    //   flag: 9
    // });
    wx.setStorageSync('hasClosedLoginOverlay', 1);
    this.setData({
      closeFlag:false
    })
    console.log(this.closeFlag,'closeFlaig0=-0=-')
  },

  closeModal() {
    this.setData({
      modalFlag: false
    });
  },

  // 检查登录状态
  checkLoginStatus() {
    const openid = wx.getStorageSync('openid');
    // 检查是否有保存的头像
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.avatarUrl) {
      this.setData({
        avatarUrl: userInfo.avatarUrl
      });
    }

    if (!openid) {
      this.setData({
        flag: 0,
        formState: {}
      })
    } else if (openid) {
      this.setData({
        flag: 1,
        isCheckingLogin: false
      });
      this.fetchUserInfo(openid);
      this.silentLogin();
      return;
    }
  },

  // 处理图片加载失败
  handleImageError: function() {
    console.log('图片加载失败');
    this.setData({
      imageLoadError: true
    });
  },
  
  // 处理图片加载成功（可选）
  handleImageLoad: function() {
    console.log('图片加载成功');
    this.setData({
      imageLoadError: false
    });
  },

  silentLogin() {
    const loginUrl = `${app.globalData.baseUrl}/login/`;

    // 在请求前显示加载状态
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.login({
      success: (res) => {
        if (res.code) {
          const loginUrlWithCode = `${loginUrl}?code=${res.code}`;

          wxutil.request.post(loginUrlWithCode).then(res => {
            // 请求成功后隐藏加载状态
            wx.hideLoading();

            if (res.data && res.data.openid) {
              wx.setStorageSync('access_token', res.data.access_token);
              wx.setStorageSync('openid', res.data.openid);

              this.fetchUserInfo(res.data.openid);
            } else {
              this.setData({
                flag: 0,
                isCheckingLogin: false
              });
            }
          }).catch(err => {
            // 请求失败后也要隐藏加载状态
            wx.hideLoading();

            this.setData({
              flag: 0,
              isCheckingLogin: false
            });
          });
        } else {
          // 获取code失败后也要隐藏加载状态
          wx.hideLoading();

          this.setData({
            flag: 0,
            isCheckingLogin: false
          });
        }
      },
      fail: (err) => {
        // wx.login失败后也要隐藏加载状态
        wx.hideLoading();

        this.setData({
          flag: 0,
          isCheckingLogin: false
        });
      },
      complete: () => {
        // 无论成功还是失败，都确保加载状态被隐藏
        wx.hideLoading();
      }
    });
  },

  fetchUserInfo(openid) {
    const doQueryUser = `${app.globalData.baseUrl}/query_user/`;
    const queryParams = {
      openid: openid
    };

    // 在请求前显示加载状态
    wx.showLoading({
      title: '加载中...',
      mask: true // 添加遮罩防止用户操作
    });

    wx.request({
      url: doQueryUser,
      method: 'GET',
      data: queryParams,
      success: (res) => {
        // 请求成功后隐藏加载状态
        wx.hideLoading();

        this.setData({
          isCheckingLogin: false
        });

        if (res.statusCode === 200 && res.data.code === 200) {
          if (res.data.data && res.data.data.length > 0) {
            wx.setStorageSync('card_id', res.data.data[0].card_id);
            // 如果服务器返回的用户数据中有头像字段，则使用服务器的头像
            if (res.data.data[0].avatar_url) {
              this.setData({
                avatarUrl: res.data.data[0].avatar_url
              });
            }

            if (res.data.data[0].status == 3) {
              this.setData({
                flag: 2,
                desc: res.data.data[0].review_failure_reason,
                formState: res.data.data[0],
              });
              wx.setStorageSync('formState', this.data.formState);
            } else if (!res.data.data[0].card_id) {
              this.setData({
                flag: 1
              });
            } else {
              this.setData({
                formState: res.data.data[0],
                flag: 2,
                imgsrc: res.data.data[0].social_security_image,
                imgsrc2: res.data.data[0].housing_fund_image,
              });
            }
          } else {
            // 用户在服务器上不存在
            this.setData({
              flag: 0
            });
          }
        } else if (res.data.error == '用户未找到') {
          // 用户未找到，需要重新登录
          this.setData({
            flag: 0,
            formState: {}
          });
        } else {
          // 处理其他错误
          wx.showToast({
            title: `网络错误`,
            icon: 'none',
            duration: 2000
          });
          this.setData({
            flag: 0
          });
        }
      },
      fail: (err) => {
        // 请求失败后也要隐藏加载状态
        wx.hideLoading();

        this.setData({
          flag: 0,
          isCheckingLogin: false
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        // 无论成功还是失败，都确保加载状态被隐藏
        wx.hideLoading();
      }
    });
  },

  handleLogin() {
    // 显示登录选择弹窗
    // this.setData({
    //   showLoginModal: true
    // });
  },

  // 修改login函数，返回Promise以便等待登录完成
  login: function () {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '登录中...',
      });

      const loginUrl = `${app.globalData.baseUrl}/login/`;

      wx.login({
        success: (res) => {
          if (res.code) {
            const loginUrlWithCode = `${loginUrl}?code=${res.code}`;

            wxutil.request.post(loginUrlWithCode).then(res => {
              wx.hideLoading();
              if (res.data && res.data.openid) {
                wx.setStorageSync('access_token', res.data.access_token);
                wx.setStorageSync('openid', res.data.openid);

                this.fetchUserInfo(res.data.openid);

                wx.showToast({
                  title: '登录成功',
                  icon: 'success'
                });

                this.setData({
                  avatarFlag: false
                })

                // 登录成功，返回openid
                resolve(res.data.openid);
              } else {
                wx.showToast({
                  title: '登录失败',
                  icon: 'none'
                });
                reject('登录失败');
              }
            }).catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              });
              reject(err);
            });
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '获取用户登录凭证失败',
              icon: 'none'
            });
            reject('获取用户登录凭证失败');
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({
            title: '调用 wx.login 失败',
            icon: 'none'
          });
          reject(err);
        }
      });
    });
  },

  hideLoginModal() {
    this.setData({
      showLoginModal: false
    });
  },

  onChooseAvatar2(e) {
    if (this.flag != 0) {
      const {
        avatarUrl
      } = e.detail;

      // 保存头像URL到本地状态
      this.setData({
        avatarUrl,
        avatarFlag:false
      });

      // 保存头像到本地存储
      const userInfo = wx.getStorageSync('userInfo') || {};
      userInfo.avatarUrl = avatarUrl;
      wx.setStorageSync('userInfo', userInfo); // 更新本地存储中的头像
    }
  },
  // 修改onChooseAvatar函数，等待登录完成后再更新头像
  onChooseAvatar(e) {
    const doUpdateUser = `${app.globalData.baseUrl}/update_user/`;
    const {
      avatarUrl
    } = e.detail;

    // 保存头像URL到本地状态
    this.setData({
      avatarUrl,
    });

    // 保存头像到本地存储
    const userInfo = wx.getStorageSync('userInfo') || {};
    userInfo.avatarUrl = avatarUrl;
    wx.setStorageSync('userInfo', userInfo); // 更新本地存储中的头像

    // 先登录，然后更新头像
    this.login().then(openid => {
      console.log(openid, '登录成功后的openid');

      // 登录成功后更新头像
      const object = {
        'avatar_url': avatarUrl
      };
      wx.request({
        url: doUpdateUser + openid,
        method: 'PUT',
        data: object,
        success(res) {
          if (res.data.code == '500') {
            wx.showToast({
              title: res.data.error,
              icon: 'error'
            });
          } else if (res.data.code === 200) {
            setTimeout(() => {
              wx.navigateBack();
            }, 1000);
          }
        },
        fail() {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    }).catch(err => {
      console.error('登录失败', err);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    });
  },

  useWechatProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        const userInfo = res.userInfo;

        // 保存头像URL到本地状态
        this.setData({
          userInfo: userInfo,
          avatarUrl: userInfo.avatarUrl
        });

        // 保存用户信息到本地存储
        wx.setStorageSync('userInfo', userInfo);

        // 登录并上传用户信息到服务器
        this.login().then(openid => {
          this.saveUserInfoToServer(userInfo);
        }).catch(err => {
          console.error('登录失败', err);
        });

        this.hideLoginModal();
      },
      fail: (err) => {
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        });
      }
    });
  },


  saveUserInfo(userInfo) {
    this.setData({
      userInfo: userInfo,
      avatarUrl: userInfo.avatarUrl // 设置头像URL
    });

    wx.setStorageSync('userInfo', userInfo);

    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });

    this.saveUserInfoToServer(userInfo);
  },

  saveUserInfoToServer(userInfo) {
    const openid = wx.getStorageSync('openid');

    if (!openid) {
      console.error('未找到openid，无法保存用户信息');
      return;
    }

    // 如果是本地文件路径，需要先上传
    if (userInfo.avatarUrl && (userInfo.avatarUrl.startsWith('wxfile://') ||
        userInfo.avatarUrl.startsWith('https://tmp/'))) {
      this.uploadAvatar(userInfo.avatarUrl, (serverUrl) => {
        userInfo.avatarUrl = serverUrl;
        this.callSaveUserInfoAPI(userInfo, openid);
      });
    } else {
      this.callSaveUserInfoAPI(userInfo, openid);
    }
  },

  uploadAvatar(filePath, callback) {
    const uploadUrl = `${app.globalData.baseUrl}/upload_avatar/`;

    wx.showLoading({
      title: '上传头像中...',
    });

    wx.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: 'avatar',
      formData: {
        'openid': wx.getStorageSync('openid')
      },
      success: (res) => {
        wx.hideLoading();

        // 解析返回的JSON
        let data;
        try {
          data = JSON.parse(res.data);
        } catch (e) {
          wx.showToast({
            title: '解析响应失败',
            icon: 'none'
          });
          return;
        }

        if (data.code === 200) {
          // 更新本地头像URL
          this.setData({
            avatarUrl: data.data.avatar_url
          });

          // 更新本地存储的用户信息
          const userInfo = wx.getStorageSync('userInfo');
          if (userInfo) {
            userInfo.avatarUrl = data.data.avatar_url;
            wx.setStorageSync('userInfo', userInfo);
          }

          callback(data.data.avatar_url);
        } else {
          wx.showToast({
            title: '头像上传失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({
          title: '头像上传失败',
          icon: 'none'
        });
      }
    });
  },

  callSaveUserInfoAPI(userInfo, openid) {
    const saveUserInfoUrl = `${app.globalData.baseUrl}/update_user_info/`;

    // 准备要发送的数据
    const data = {
      openid: openid,
      nickname: userInfo.nickName,
      avatar_url: userInfo.avatarUrl,
      // 可以添加其他需要更新的用户信息字段
    };

    wx.request({
      url: saveUserInfoUrl,
      method: 'POST',
      data: data,
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          console.log('用户信息保存成功', res.data);
        } else {
          console.error('保存用户信息失败', res.data);
        }
      },
      fail: (err) => {
        console.error('保存用户信息到服务器失败', err);
      }
    });
  },

  onLoad: function () {
    // 检查是否有保存的头像
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.avatarUrl) {
      this.setData({
        avatarUrl: userInfo.avatarUrl
      });
    }
    const hasClosedLoginOverlay = wx.getStorageSync('hasClosedLoginOverlay');
    this.setData({
      closeFlag: hasClosedLoginOverlay != 1 ? true : false
    })
  },

  onShow: function () {
    if (this.data.isFromImagePreview) {
      this.setData({
        isFromImagePreview: false, // 重置标志
      });
      return;
    }
    const www = wx.getStorageSync('userInfo')
    console.log(www.avatarUrl, 'www-0-=')
    if (www.avatarUrl) {
      this.setData({
        avatarUrl: www.avatarUrl
      })
    } else {
      this.setData({
        avatarUrl: './images/default.jpg'
      })
    }

    this.checkLoginStatus();
  },

  init: function () {
    const openid = wx.getStorageSync('openid');
    if (!openid) {
      this.setData({
        flag: 0,
        "formState": {}
      })
    } else {
      this.fetchUserInfo(openid);
    }
  },

  showimg: function () {
    if (this.data.formState.social_security_image) {
      this.setData({
        openImg: true,
        imgsrc: this.data.formState.social_security_image
      });
    } else {
      wx.showToast({
        title: "暂无",
        icon: "none"
      });
    }
  },

  showimg2: function () {
    if (this.data.formState.housing_fund_image) {
      this.setData({
        openImg2: true,
        imgsrc2: this.data.formState.housing_fund_image
      });
    } else {
      wx.showToast({
        title: "暂无",
        icon: "none"
      });
    }

  },

  hideModal3: function () {
    this.setData({
      showIdCardsSection: false
    })
  },

  stopPropagation: (e) => {
    return false;
  },

  onContextMenu: function () {
    return false;
  },

  onTouchStart: function () {
    return false;
  },

  hideModal: function () {
    this.setData({
      openImg: false
    });
  },
  closePopup: function () {
    this.setData({
      showIdCardsSection: false
    });
  },

  hideModal2: function () {
    this.setData({
      openImg2: false
    });
  }
});